package furns.web;

import furns.entity.Member;
import furns.service.MemberService;
import furns.service.impl.MemberServiceImpl;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;

@SuppressWarnings("all")
@WebServlet(name = "LoginServlet", urlPatterns = "/loginServlet")
public class LoginServlet extends HttpServlet {
    //创建一个memberService对象,便于调用其方法
    private MemberService memberService = new MemberServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        System.out.println("LoginServlet 被调用");
        //获取用户输入的用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Member member = new Member(null, username, password, null);
        if (memberService.login(member) != null) {
            //表示数据库中存在用户输入的数据，因此登录成功
            request.getRequestDispatcher("/views/member/login_ok.jsp").forward(request, response);
        } else {
            //登录失败，跳转到登录页面，并提示用户名或密码错误
            //将提示信息保存到request域中。因为是请求转发，因此是同一个request对象
            request.setAttribute("msg", "用户名或密码错误");
            //密码错误，将用户输入的用户名保存到request域中并显示在登录页面中
            request.setAttribute("username", username);
            request.getRequestDispatcher("/views/member/login.jsp").forward(request, response);
        }
    }
}